package eiisan.lock;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 任务 阶段汇总 执行
 * @author eii
 * @time 2020/10/30 10:20 下午
 */
public class CyclicBarrierTest2 {
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(2,()->{
        System.out.println("阶段 ok");
    });

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(2);

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread() + "Step1");
                    Thread.sleep(3000);
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread() + "Step2");
                    Thread.sleep(6000);
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread() + "Step3");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread() + "Step1");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread() + "Step2");
                    cyclicBarrier.await();
                    System.out.println(Thread.currentThread() + "Step3");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });

        executorService.shutdown();
    }

}
